/**
 * @description User API 路由
 *
 *
 **/


const router = require('koa-router')()

const { isExist, registerUser, login, deleteCurUser} =  require('../../controller/user')
const userValidate = require('../../validator/user')
const { genValidator } = require('../../middleware/validator')
const { isTest } = require('../../utils/env')
const { logincheck } = require('../../middleware/loginChecks')

router.prefix('/api/user')

router.post('/register', genValidator(userValidate),  async (ctx, next) => {
  const { userName, password , gender } = ctx.request.body
  ctx.body = await registerUser({ userName, password, gender})

})

router.post('/isExist', async (ctx,next) => {
  const { userName } = ctx.request.body
  console.log('userName',userName)
  // 交给controller 层进行业务逻辑处理
  // 返回统一数据格式
  ctx.body = await isExist(userName)

})

router.post('/login' , async (ctx,next) => {
  const { userName, password } = ctx.request.body
  // 交给controller 处理
  ctx.body = await login(ctx, userName, password)

})

// 删除用户
router.post('/delete', logincheck, async (ctx, next) => {
  const { userName } = ctx.session.userInfo
  if(isTest) {
    ctx.body = await deleteCurUser(userName)
  }

} )

module.exports = router